#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/11 16:01
    Desc  :
--------------------------------------
"""
from mongoengine import QuerySet


class QueryListUtils:
    """
    查询过滤器
    """

    def __init__(self, iterable: dict):
        self.iterable = iterable
        page, size = self.iterable.get('page'), self.iterable.get('size')
        if page:
            del self.iterable['page']
        if size:
            del self.iterable['size']

    def filter(self):
        """
        正常查询
        :return:
        """

        for i in list(self.iterable.keys()):
            if self.iterable[i] is None:
                self.iterable.pop(i)
        return self.iterable

    def filter_by_icontains(self):
        """
        不区分大小写的查询
        :return:
        """
        queryDict = {}

        for i in list(self.iterable.keys()):
            if self.iterable[i] is None:
                self.iterable.pop(i)
            else:
                queryDict[f'{i}' + '__icontains'] = self.iterable[i]

        return queryDict

    def filter_by_contains(self):
        """
        区分大小写的查询
        :return:
        """
        queryDict = {}

        for i in list(self.iterable.keys()):
            if self.iterable[i] is None:
                self.iterable.pop(i)
            else:
                queryDict[f'{i}' + '__contains'] = self.iterable[i]

        return queryDict

    def filter_by(self, queries: str):
        """
        字符串正则查询
        :param queries:
            exact – 字符串型字段完全匹配这个值
            iexact – 字符串型字段完全匹配这个值（大小写敏感）
            contains – 字符串字段包含这个值
            icontains – 字符串字段包含这个值（大小写敏感）
            startswith – 字符串字段由这个值开头
            istartswith – 字符串字段由这个值开头（大小写敏感）
            endswith – 字符串字段由这个值结尾
            iendswith – 字符串字段由这个值结尾（大小写敏感）
            match – 执行 $elemMatch 操作，所以你可以使用一个数组中的 document 实例
        :example: QueryListUtils(form).filter_by('icontains')
        :return:
        """
        queryDict = {}

        for i in list(self.iterable.keys()):
            if self.iterable[i] is None:
                self.iterable.pop(i)
            else:
                queryDict[f'{i}' + '__' + queries] = self.iterable[i]

        return queryDict
